"use client"

import { useState, useEffect, useRef } from 'react'
import { textStyles, fontSizes, fontWeights } from '../../lib/fontConfig'

interface Course {
  lesson_number: string
  course_name: string
  target_char: string
}

interface DragCombineDisplayProps {
  currentCourse?: Course
}

// 数据库表结构接口（预留）
interface ZigenTable {
  id: string
  character: string
  meaning: string
  category: string
}

interface BushouTable {
  id: string
  radical: string
  position: string
  meaning: string
}

interface BihuaTable {
  id: string
  stroke: string
  order: number
  description: string
}

interface CompoundCharTable {
  id: string
  compound_char: string
  components: string[]
  pronunciation: string
  meaning: string
  stroke_count: number
  words: string[]
  sentences: string[]
}

// 拖拽元素接口
interface DragElement {
  id: string
  character: string
  type: 'zigen' | 'bushou' | 'bihua'
  color: string
}

// 组合框接口
interface CombineBox {
  id: string
  position: number
  content: string | null
  isFixed: boolean
  isActive: boolean
}

export function DragCombineDisplay({ currentCourse }: DragCombineDisplayProps) {
  const [dragElements, setDragElements] = useState<DragElement[]>([])
  const [combineBoxes, setCombineBoxes] = useState<CombineBox[]>([])
  const [currentCompound, setCurrentCompound] = useState<CompoundCharTable | null>(null)
  const [draggedElement, setDraggedElement] = useState<DragElement | null>(null)
  const [isValidating, setIsValidating] = useState(false)
  const [completedChars, setCompletedChars] = useState<string[]>([])

  // 模拟数据库数据（后续替换为真实API调用）
  const mockData = {
    // 字根数据
    zigens: [
      { id: 'z1', character: '木', type: 'zigen' as const, color: 'from-green-400 to-green-500' },
      { id: 'z2', character: '人', type: 'zigen' as const, color: 'from-blue-400 to-blue-500' },
      { id: 'z3', character: '口', type: 'zigen' as const, color: 'from-purple-400 to-purple-500' },
    ],
    // 部首数据
    bushous: [
      { id: 'b1', character: '亻', type: 'bushou' as const, color: 'from-orange-400 to-orange-500' },
      { id: 'b2', character: '氵', type: 'bushou' as const, color: 'from-cyan-400 to-cyan-500' },
      { id: 'b3', character: '艹', type: 'bushou' as const, color: 'from-lime-400 to-lime-500' },
    ],
    // 笔画数据
    bihuas: [
      { id: 'h1', character: '一', type: 'bihua' as const, color: 'from-gray-400 to-gray-500' },
      { id: 'h2', character: '丨', type: 'bihua' as const, color: 'from-slate-400 to-slate-500' },
      { id: 'h3', character: '丿', type: 'bihua' as const, color: 'from-stone-400 to-stone-500' },
    ],
    // 复合字数据库（预设的正确组合）
    compounds: [
      {
        id: 'c1',
        compound_char: '休',
        components: ['人', '木'],
        pronunciation: 'xiū',
        meaning: '休息、停止',
        stroke_count: 6,
        words: ['休息', '休假', '休学', '午休'],
        sentences: ['小明在树下休息。', '今天是休息日。']
      },
      {
        id: 'c2',
        compound_char: '林',
        components: ['木', '木'],
        pronunciation: 'lín',
        meaning: '树林、森林',
        stroke_count: 8,
        words: ['森林', '树林', '林子', '竹林'],
        sentences: ['森林里有很多动物。', '我们去树林里玩。']
      },
      {
        id: 'c3',
        compound_char: '杏',
        components: ['木', '口'],
        pronunciation: 'xìng',
        meaning: '杏树、杏子',
        stroke_count: 7,
        words: ['杏花', '杏子', '杏树', '银杏'],
        sentences: ['春天杏花开了。', '杏子很甜很好吃。']
      }
    ]
  }

  // 初始化数据
  useEffect(() => {
    const char = currentCourse?.target_char || '木'
    
    // 合并所有可拖拽元素
    const allElements = [
      ...mockData.zigens,
      ...mockData.bushous,
      ...mockData.bihuas
    ]
    setDragElements(allElements)

    // 初始化组合框（第一个框固定当前字根）
    const initialBoxes: CombineBox[] = [
      {
        id: 'box1',
        position: 1,
        content: char,
        isFixed: true,
        isActive: false
      },
      {
        id: 'box2',
        position: 2,
        content: null,
        isFixed: false,
        isActive: true
      }
    ]
    setCombineBoxes(initialBoxes)
  }, [currentCourse])

  // 拖拽开始
  const handleDragStart = (element: DragElement) => {
    setDraggedElement(element)
  }

  // 拖拽结束
  const handleDragEnd = () => {
    setDraggedElement(null)
  }

  // 放置到组合框
  const handleDrop = async (boxId: string) => {
    if (!draggedElement) return

    const targetBox = combineBoxes.find(box => box.id === boxId)
    if (!targetBox || targetBox.isFixed || !targetBox.isActive) return

    // 更新组合框内容
    const updatedBoxes = combineBoxes.map(box =>
      box.id === boxId
        ? { ...box, content: draggedElement.character, isActive: false }
        : box
    )
    setCombineBoxes(updatedBoxes)

    // 验证组合
    await validateCombination(updatedBoxes)
  }

  // 验证组合是否正确
  const validateCombination = async (boxes: CombineBox[]) => {
    setIsValidating(true)
    
    // 获取当前组合的字符
    const currentComponents = boxes
      .filter(box => box.content)
      .map(box => box.content!)
      .sort()

    // 在复合字数据库中查找匹配的组合
    const matchedCompound = mockData.compounds.find(compound =>
      compound.components.sort().join('') === currentComponents.join('')
    )

    if (matchedCompound) {
      // 找到匹配的复合字
      setCurrentCompound(matchedCompound)
      setCompletedChars([...completedChars, matchedCompound.compound_char])
      
      // 检查是否需要更多组件
      if (matchedCompound.components.length > currentComponents.length) {
        // 需要更多组件，添加新的组合框
        const nextPosition = boxes.length + 1
        const newBox: CombineBox = {
          id: `box${nextPosition}`,
          position: nextPosition,
          content: null,
          isFixed: false,
          isActive: true
        }
        setCombineBoxes([...boxes, newBox])
      }
    } else {
      // 没有找到匹配的组合，检查是否是部分正确的组合
      const partialMatch = mockData.compounds.find(compound =>
        currentComponents.every(comp => compound.components.includes(comp))
      )
      
      if (partialMatch && partialMatch.components.length > currentComponents.length) {
        // 部分正确，需要更多组件
        const nextPosition = boxes.length + 1
        const newBox: CombineBox = {
          id: `box${nextPosition}`,
          position: nextPosition,
          content: null,
          isFixed: false,
          isActive: true
        }
        setCombineBoxes([...boxes, newBox])
      } else {
        // 组合错误，重置最后一个框
        const resetBoxes = boxes.map(box =>
          !box.isFixed && box.content === draggedElement?.character
            ? { ...box, content: null, isActive: true }
            : box
        )
        setCombineBoxes(resetBoxes)
      }
    }

    setIsValidating(false)
  }

  // 重置组合
  const resetCombination = () => {
    const char = currentCourse?.target_char || '木'
    const resetBoxes: CombineBox[] = [
      {
        id: 'box1',
        position: 1,
        content: char,
        isFixed: true,
        isActive: false
      },
      {
        id: 'box2',
        position: 2,
        content: null,
        isFixed: false,
        isActive: true
      }
    ]
    setCombineBoxes(resetBoxes)
    setCurrentCompound(null)
  }

  return (
    <div className="h-full flex flex-col p-3 space-y-4">
      {/* 标题区域 */}
      <div className="text-center">
        <h2 className={`${textStyles.mainTitle} text-purple-700 mb-2 drop-shadow-sm`}>
          🧩 拖拽组合游戏
        </h2>
        <p className={`${textStyles.description} text-gray-600`}>
          把字根、部首、笔画拖到框里，组成新的汉字吧！
        </p>
      </div>

      {/* 主要内容区域 */}
      <div className="flex-1 grid grid-cols-3 gap-4 min-h-0">
        {/* 左侧：部首笔画库 */}
        <div className="bg-white/90 backdrop-blur-sm rounded-xl p-4 shadow-lg border border-blue-100">
          <h3 className={`${textStyles.sectionTitle} text-blue-700 mb-3 text-center font-bold drop-shadow-sm`}>
            📚 字符库
          </h3>
          
          <div className="space-y-4">
            {/* 字根区 */}
            <div>
              <h4 className={`${textStyles.tag} text-green-700 mb-2 font-bold`}>
                🌱 字根
              </h4>
              <div className="flex flex-wrap gap-2">
                {mockData.zigens.map((element) => (
                  <div
                    key={element.id}
                    draggable
                    onDragStart={() => handleDragStart(element)}
                    onDragEnd={handleDragEnd}
                    className={`
                      w-12 h-12 bg-gradient-to-br ${element.color} 
                      rounded-lg flex items-center justify-center cursor-grab
                      text-white font-bold text-lg shadow-md
                      hover:scale-110 hover:shadow-lg transition-all duration-300
                      active:cursor-grabbing active:scale-95
                    `}
                  >
                    {element.character}
                  </div>
                ))}
              </div>
            </div>

            {/* 部首区 */}
            <div>
              <h4 className={`${textStyles.tag} text-orange-700 mb-2 font-bold`}>
                🏗️ 部首
              </h4>
              <div className="flex flex-wrap gap-2">
                {mockData.bushous.map((element) => (
                  <div
                    key={element.id}
                    draggable
                    onDragStart={() => handleDragStart(element)}
                    onDragEnd={handleDragEnd}
                    className={`
                      w-12 h-12 bg-gradient-to-br ${element.color} 
                      rounded-lg flex items-center justify-center cursor-grab
                      text-white font-bold text-lg shadow-md
                      hover:scale-110 hover:shadow-lg transition-all duration-300
                      active:cursor-grabbing active:scale-95
                    `}
                  >
                    {element.character}
                  </div>
                ))}
              </div>
            </div>

            {/* 笔画区 */}
            <div>
              <h4 className={`${textStyles.tag} text-gray-700 mb-2 font-bold`}>
                ✏️ 笔画
              </h4>
              <div className="flex flex-wrap gap-2">
                {mockData.bihuas.map((element) => (
                  <div
                    key={element.id}
                    draggable
                    onDragStart={() => handleDragStart(element)}
                    onDragEnd={handleDragEnd}
                    className={`
                      w-12 h-12 bg-gradient-to-br ${element.color} 
                      rounded-lg flex items-center justify-center cursor-grab
                      text-white font-bold text-lg shadow-md
                      hover:scale-110 hover:shadow-lg transition-all duration-300
                      active:cursor-grabbing active:scale-95
                    `}
                  >
                    {element.character}
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* 中间：拖拽组合区 */}
        <div className="bg-white/90 backdrop-blur-sm rounded-xl p-4 shadow-lg border border-purple-100">
          <h3 className={`${textStyles.sectionTitle} text-purple-700 mb-3 text-center font-bold drop-shadow-sm`}>
            🎯 组合区域
          </h3>
          
          <div className="flex flex-col items-center space-y-4">
            {/* 组合框 */}
            <div className="flex items-center space-x-2">
              {combineBoxes.map((box, index) => (
                <div key={box.id} className="flex items-center">
                  <div
                    onDragOver={(e) => e.preventDefault()}
                    onDrop={() => handleDrop(box.id)}
                    className={`
                      w-16 h-16 border-2 border-dashed rounded-xl
                      flex items-center justify-center text-2xl font-bold
                      transition-all duration-300
                      ${box.isFixed
                        ? 'bg-green-100 border-green-400 text-green-700'
                        : box.isActive
                        ? 'bg-blue-50 border-blue-400 text-blue-600 hover:bg-blue-100'
                        : box.content
                        ? 'bg-purple-100 border-purple-400 text-purple-700'
                        : 'bg-gray-50 border-gray-300 text-gray-400'
                      }
                    `}
                  >
                    {box.content || '?'}
                  </div>
                  {index < combineBoxes.length - 1 && (
                    <span className="text-2xl text-gray-400 mx-2">+</span>
                  )}
                </div>
              ))}
            </div>

            {/* 等号和结果 */}
            <div className="flex items-center space-x-4">
              <span className="text-3xl text-gray-600">=</span>
              <div className={`
                w-20 h-20 border-2 rounded-xl flex items-center justify-center
                text-3xl font-bold transition-all duration-500
                ${currentCompound
                  ? 'bg-yellow-100 border-yellow-400 text-yellow-700 animate-pulse'
                  : 'bg-gray-50 border-gray-300 text-gray-400'
                }
              `}>
                {isValidating ? '⏳' : currentCompound?.compound_char || '?'}
              </div>
            </div>

            {/* 控制按钮 */}
            <div className="flex space-x-2">
              <button
                onClick={resetCombination}
                className={`
                  ${textStyles.secondaryButton} px-4 py-2 
                  bg-red-500 text-white rounded-lg
                  hover:bg-red-600 hover:scale-105 
                  transition-all duration-300
                `}
              >
                🔄 重新开始
              </button>
            </div>

            {/* 已完成的字符展示 */}
            {completedChars.length > 0 && (
              <div className="mt-4">
                <h4 className={`${textStyles.tag} text-green-700 mb-2 font-bold text-center`}>
                  🎉 已完成的字
                </h4>
                <div className="flex flex-wrap gap-2 justify-center">
                  {completedChars.map((char, index) => (
                    <div
                      key={index}
                      className="w-10 h-10 bg-green-100 border-2 border-green-400 
                               rounded-lg flex items-center justify-center
                               text-green-700 font-bold"
                    >
                      {char}
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* 右侧：复合字解释区 */}
        <div className="bg-white/90 backdrop-blur-sm rounded-xl p-4 shadow-lg border border-green-100">
          <h3 className={`${textStyles.sectionTitle} text-green-700 mb-3 text-center font-bold drop-shadow-sm`}>
            📖 字词解释
          </h3>
          
          {currentCompound ? (
            <div className="space-y-4">
              {/* 基本信息 */}
              <div className="text-center">
                <div className={`${textStyles.primaryCharacter} text-green-700 mb-2`}>
                  {currentCompound.compound_char}
                </div>
                <div className={`${textStyles.description} text-blue-600 font-semibold`}>
                  🔊 读音：{currentCompound.pronunciation}
                </div>
                <div className={`${textStyles.description} text-purple-600 font-semibold`}>
                  ✏️ 笔画：{currentCompound.stroke_count}画
                </div>
              </div>

              {/* 含义 */}
              <div className="bg-blue-50 rounded-lg p-3">
                <h4 className={`${textStyles.tag} text-blue-700 mb-2 font-bold`}>
                  💭 含义
                </h4>
                <p className={`${textStyles.caption} text-gray-700`}>
                  {currentCompound.meaning}
                </p>
              </div>

              {/* 组词 */}
              <div className="bg-purple-50 rounded-lg p-3">
                <h4 className={`${textStyles.tag} text-purple-700 mb-2 font-bold`}>
                  📝 组词
                </h4>
                <div className="flex flex-wrap gap-2">
                  {currentCompound.words.map((word, index) => (
                    <span
                      key={index}
                      className="bg-purple-200 text-purple-800 px-2 py-1 rounded-full text-sm font-medium"
                    >
                      {word}
                    </span>
                  ))}
                </div>
              </div>

              {/* 造句 */}
              <div className="bg-green-50 rounded-lg p-3">
                <h4 className={`${textStyles.tag} text-green-700 mb-2 font-bold`}>
                  📚 造句
                </h4>
                <div className="space-y-2">
                  {currentCompound.sentences.map((sentence, index) => (
                    <p
                      key={index}
                      className={`${textStyles.caption} text-gray-700 bg-white rounded-lg p-2`}
                    >
                      {sentence}
                    </p>
                  ))}
                </div>
              </div>
            </div>
          ) : (
            <div className="text-center text-gray-500 mt-8">
              <div className="text-6xl mb-4">🤔</div>
              <p className={`${textStyles.description}`}>
                拖拽字符到组合区，<br />
                看看能组成什么字吧！
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  )
} 